﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace NGS.BioSequenceIO
{
    class FastaFileReader
    {
        Stream stream;
        StreamReader sr;
        string nextCaption;
        public FastaFileReader(string filename)
        {
            FileStream fs = File.OpenRead(filename);
            if (filename.IndexOf(".gz") > 0)
            {
                GZipStream gstream = new GZipStream(fs, CompressionMode.Decompress);
                stream = (Stream)gstream;
            }
            else
            {
                stream = (Stream)fs;
            }
            sr = new StreamReader(stream, Encoding.ASCII);
            nextCaption = sr.ReadLine();
        }
        public Sequence GetSequence()
        {
            if (nextCaption == null) return null;
            StringBuilder sb = new StringBuilder();
            Sequence seq = new Sequence();
            seq.caption = nextCaption;
            string line = sr.ReadLine();
            while (line != null && line.Length > 0 && line[0] != '>')
            {
                sb.Append(line);
                line = sr.ReadLine();
            }
            nextCaption = line;
            seq.bases = sb.ToString();
            return seq;
        }
        public List<Sequence> GetAllSequence()
        {
            List<Sequence> listSequence = new List<Sequence>();
            Sequence sequence = GetSequence();
            while (sequence != null)
            {
                listSequence.Add(sequence);
                sequence = GetSequence();
            }
            return listSequence;
        }
    }
}
